#!/bin/bash

# 部署脚本
# 用法: ./scripts/deploy.sh [dev|prod]

set -e

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 打印带颜色的消息
print_message() {
    local color=$1
    local message=$2
    echo -e "${color}${message}${NC}"
}

# 检查参数
if [ $# -eq 0 ]; then
    print_message $RED "错误: 请指定部署环境 (dev 或 prod)"
    echo "用法: $0 [dev|prod]"
    exit 1
fi

ENVIRONMENT=$1

if [ "$ENVIRONMENT" != "dev" ] && [ "$ENVIRONMENT" != "prod" ]; then
    print_message $RED "错误: 环境参数必须是 'dev' 或 'prod'"
    exit 1
fi

print_message $BLUE "🚀 开始部署到 $ENVIRONMENT 环境..."

# 检查 Node.js 和 npm
if ! command -v node &> /dev/null; then
    print_message $RED "错误: Node.js 未安装"
    exit 1
fi

if ! command -v npm &> /dev/null; then
    print_message $RED "错误: npm 未安装"
    exit 1
fi

print_message $YELLOW "📋 运行健康检查..."
npm run health-check

if [ $? -ne 0 ]; then
    print_message $RED "❌ 健康检查失败，部署终止"
    exit 1
fi

print_message $GREEN "✅ 健康检查通过"

# 清理旧的构建文件
print_message $YELLOW "🧹 清理旧的构建文件..."
rm -rf dist

# 安装依赖
print_message $YELLOW "📦 安装依赖..."
npm ci

# 运行测试
print_message $YELLOW "🧪 运行测试..."
npm run test:run

if [ $? -ne 0 ]; then
    print_message $RED "❌ 测试失败，部署终止"
    exit 1
fi

print_message $GREEN "✅ 测试通过"

# 构建应用
print_message $YELLOW "🔨 构建应用 ($ENVIRONMENT 环境)..."
if [ "$ENVIRONMENT" = "prod" ]; then
    npm run build:prod
else
    npm run build:dev
fi

if [ $? -ne 0 ]; then
    print_message $RED "❌ 构建失败，部署终止"
    exit 1
fi

print_message $GREEN "✅ 构建完成"

# 检查构建结果
if [ ! -d "dist" ]; then
    print_message $RED "❌ 构建目录不存在"
    exit 1
fi

if [ ! -f "dist/index.html" ]; then
    print_message $RED "❌ 主页面文件不存在"
    exit 1
fi

print_message $GREEN "✅ 构建文件验证通过"

# 显示构建统计
print_message $BLUE "📊 构建统计:"
echo "构建目录大小: $(du -sh dist | cut -f1)"
echo "文件数量: $(find dist -type f | wc -l)"
echo "主要文件:"
ls -lh dist/*.html dist/manifest.webmanifest 2>/dev/null || true
echo ""
echo "JavaScript 文件:"
ls -lh dist/js/*.js | head -5
echo ""
echo "CSS 文件:"
ls -lh dist/assets/*.css | head -5

# 部署到服务器 (这里只是示例，实际部署需要根据具体环境配置)
print_message $YELLOW "🚀 准备部署..."

if [ "$ENVIRONMENT" = "prod" ]; then
    print_message $BLUE "生产环境部署配置:"
    echo "- 目标服务器: production-server.com"
    echo "- 部署路径: /var/www/html/"
    echo "- 备份策略: 保留最近3个版本"
    
    # 这里添加实际的生产环境部署逻辑
    # 例如: rsync, scp, 或调用 CI/CD 系统
    print_message $YELLOW "⚠️  请手动执行生产环境部署，或配置自动化部署脚本"
    
else
    print_message $BLUE "开发环境部署配置:"
    echo "- 目标服务器: dev-server.com"
    echo "- 部署路径: /var/www/dev/"
    
    # 这里添加实际的开发环境部署逻辑
    print_message $YELLOW "⚠️  请手动执行开发环境部署，或配置自动化部署脚本"
fi

# 生成部署报告
DEPLOY_TIME=$(date '+%Y-%m-%d %H:%M:%S')
DEPLOY_REPORT="deploy-report-$(date '+%Y%m%d-%H%M%S').txt"

cat > "$DEPLOY_REPORT" << EOF
部署报告
========

部署时间: $DEPLOY_TIME
部署环境: $ENVIRONMENT
构建版本: $(node -p "require('./package.json').version")
Git 提交: $(git rev-parse --short HEAD 2>/dev/null || echo "未知")

构建统计:
- 构建目录大小: $(du -sh dist | cut -f1)
- 文件数量: $(find dist -type f | wc -l)
- 压缩文件数量: $(find dist -name "*.gz" | wc -l)

主要文件:
$(ls -lh dist/*.html dist/manifest.webmanifest 2>/dev/null || echo "无")

JavaScript 文件 (前5个):
$(ls -lh dist/js/*.js | head -5)

CSS 文件 (前5个):
$(ls -lh dist/assets/*.css | head -5)

部署状态: 构建完成，等待上传
EOF

print_message $GREEN "📄 部署报告已生成: $DEPLOY_REPORT"

print_message $GREEN "🎉 部署准备完成！"
print_message $BLUE "📝 后续步骤:"
echo "1. 检查构建文件: ls -la dist/"
echo "2. 本地预览: npm run preview"
echo "3. 上传到服务器"
echo "4. 验证部署结果"
echo "5. 监控应用状态"

print_message $YELLOW "💡 提示:"
echo "- 生产环境部署前请确保已经过充分测试"
echo "- 部署后请验证所有功能正常工作"
echo "- 监控错误日志和性能指标"